import { topicApi } from "~/utils/api";
import type {
  TopicWithUser,
  TopicQueryParams,
  CreateTopicRequest,
  UpdateTopicRequest,
  ReviewTopicRequest,
} from "~/types/topic";
import { useUserStore } from "~/stores/user";
// 定义类型接口
interface DomainStat {
  domain: string;
  count: number;
}

// 使用导入的类型
type TopicCreateData = CreateTopicRequest;
type TopicUpdateData = UpdateTopicRequest;
type TopicReviewData = ReviewTopicRequest;

export const useTopics = () => {
  const userStore = useUserStore();
  // 响应式数据
  const topics = ref<TopicWithUser[]>([]);
  const selectedTopic = ref<TopicWithUser | null>(null);
  const domains = ref([
    { id: "html", name: "HTML", count: 0 },
    { id: "js", name: "JavaScript", count: 0 },
    { id: "css", name: "CSS", count: 0 },
    { id: "vue", name: "Vue", count: 0 },
    { id: "工程化", name: "工程化", count: 0 },
  ]);
  const difficultiesENUM = ref([
    { label: "基础", value: "基础" },
    { label: "中等", value: "中等" },
    { label: "困难", value: "困难" },
  ]);
  const DomainsENUM = ref([
    { label: "HTML", value: "html" },
    { label: "JavaScript", value: "js" },
    { label: "CSS", value: "css" },
    { label: "Vue", value: "vue" },
    { label: "工程化", value: "工程化" },
  ]);
  const ReviewStatusENUM = ref([
    { label: "待审核", value: "pending" },
    { label: "已通过", value: "approved" },
    { label: "已拒绝", value: "rejected" },
  ]);
  const selectedDomain = ref("html");
  const loading = ref(false);
  const error = ref<string | null>(null);

  // 分页相关状态
  const pagination = ref({
    current: 1,
    pageSize: 10,
    total: 0,
    totalPages: 0,
  });

  // 计算属性：根据选择的领域过滤题目
  const filteredTopics = computed(() => {
    return topics.value.filter(
      (topic) => topic.domain === selectedDomain.value
    );
  });

  // 获取题目列表
  const fetchTopics = async (params?: TopicQueryParams, type?: string) => {
    try {
      loading.value = true;
      error.value = null;

      // 合并分页参数
      const queryParams = {
        ...params,
        page: params?.page || pagination.value.current,
        limit: params?.limit || pagination.value.pageSize,
        submitterId: params?.submitterId || userStore.user?.id,
      };

      const response = await topicApi.getTopicsApi(queryParams, type);
      if (response.success) {
        topics.value = response.data.topics;
        // 更新分页信息
        pagination.value = {
          current: response.data.page,
          pageSize: response.data.limit,
          total: response.data.total,
          totalPages: response.data.totalPages,
        };
      }
    } catch (err) {
      error.value = "获取题目列表失败";
      console.error("获取题目列表失败:", err);
    } finally {
      loading.value = false;
    }
  };

  // 获取题目详情
  const getTopicById = async (id: number): Promise<TopicWithUser | null> => {
    try {
      loading.value = true;
      error.value = null;
      const response = await topicApi.getTopicByIdApi(id);
      if (response.success) {
        return response.data;
      }
      return null;
    } catch (err) {
      error.value = "获取题目详情失败";
      console.error("获取题目详情失败:", err);
      return null;
    } finally {
      loading.value = false;
    }
  };

  // 获取统计信息
  const fetchStats = async (params?: TopicQueryParams) => {
    try {
      const response = await topicApi.getTopicStatsApi(params);
      if (response.success) {
        // 更新领域统计
        domains.value.forEach((domain) => {
          const stat = response.data.domainStats.find(
            (s: DomainStat) => s.domain === domain.id
          );
          if (stat) {
            domain.count = stat.count;
          }
        });
      }
    } catch (err) {
      console.error("获取统计信息失败:", err);
    }
  };

  // 选择题目
  const selectTopic = (topicId: number) => {
    selectedTopic.value =
      topics.value.find((topic) => topic.id === topicId) || null;
  };

  // 选择领域
  const selectDomain = (domainId: string) => {
    selectedDomain.value = domainId;
    // 如果当前选中的题目不在新领域中，清空选择
    if (selectedTopic.value && selectedTopic.value.domain !== domainId) {
      selectedTopic.value = null;
    }

    // 切换领域后，如果有题目列表，自动选择第一道题
    nextTick(() => {
      if (filteredTopics.value.length > 0) {
        selectTopic(filteredTopics.value[0].id);
      }
    });
  };

  // 初始化数据
  const initialize = async (fetchParams?: TopicQueryParams) => {
    await Promise.all([
      fetchTopics({ ...fetchParams }),
      fetchStats({ ...fetchParams }),
    ]);
    // 如果有题目，选择第一个
    if (filteredTopics.value.length > 0) {
      selectTopic(filteredTopics.value[0].id);
    }
  };

  // 创建题目
  const createTopic = async (topicData: TopicCreateData) => {
    try {
      loading.value = true;
      const response = await topicApi.createTopicApi(topicData);
      if (response.success) {
        // 重新获取题目列表
        await fetchTopics();
        return response.data;
      }
    } catch (err) {
      error.value = "创建题目失败";
      console.error("创建题目失败:", err);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  // 更新题目
  const updateTopic = async (id: number, topicData: TopicUpdateData) => {
    try {
      loading.value = true;
      const response = await topicApi.updateTopicApi(id, topicData);
      if (response.success) {
        // 重新获取题目列表
        await fetchTopics();
        return response.data;
      }
    } catch (err) {
      error.value = "更新题目失败";
      console.error("更新题目失败:", err);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  // 删除题目
  const deleteTopic = async (id: number) => {
    try {
      loading.value = true;
      const response = await topicApi.deleteTopicApi(id);
      if (response.success) {
        // 重新获取题目列表
        await fetchTopics();
        // 如果删除的是当前选中的题目，清空选择
        if (selectedTopic.value?.id === id) {
          selectedTopic.value = null;
        }
      }
    } catch (err) {
      error.value = "删除题目失败";
      console.error("删除题目失败:", err);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  // 审核题目
  const reviewTopic = async (id: number, reviewData: TopicReviewData) => {
    try {
      loading.value = true;
      const response = await topicApi.reviewTopicApi(id, reviewData);
      if (response.success) {
        // 重新获取题目列表
        await fetchTopics();
        return response.data;
      }
    } catch (err) {
      error.value = "审核题目失败";
      console.error("审核题目失败:", err);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  // 收藏操作
  const starTopic = async (id: number, action: "increment" | "decrement") => {
    try {
      const response = await topicApi.starTopicApi(id, { action });
      if (response.success) {
        // 更新本地数据
        const topic = topics.value.find((t) => t.id === id);
        if (topic) {
          if (action === "increment") {
            topic.starCount++;
          } else {
            topic.starCount = Math.max(0, topic.starCount - 1);
          }
        }
        // 如果当前选中的题目，也更新
        if (selectedTopic.value?.id === id) {
          if (action === "increment") {
            selectedTopic.value.starCount++;
          } else {
            selectedTopic.value.starCount = Math.max(
              0,
              selectedTopic.value.starCount - 1
            );
          }
        }
        return response.data;
      }
    } catch (err) {
      error.value = "收藏操作失败";
      console.error("收藏操作失败:", err);
      throw err;
    }
  };

  // 分页相关方法
  const changePage = (page: number, pageSize?: number) => {
    pagination.value.current = page;
    if (pageSize) {
      pagination.value.pageSize = pageSize;
    }
    // 重新获取数据
    fetchTopics({
      page: pagination.value.current,
      limit: pagination.value.pageSize,
    });
  };

  const changePageSize = (current: number, size: number) => {
    pagination.value.current = 1; // 重置到第一页
    pagination.value.pageSize = size;
    // 重新获取数据
    fetchTopics({
      page: 1,
      limit: size,
    });
  };

  // 题目导航方法
  const goToPreviousTopic = () => {
    if (!selectedTopic.value) return;
    
    const currentIndex = filteredTopics.value.findIndex(
      topic => topic.id === selectedTopic.value!.id
    );
    
    if (currentIndex > 0) {
      selectTopic(filteredTopics.value[currentIndex - 1].id);
    }
  };

  const goToNextTopic = () => {
    if (!selectedTopic.value) return;
    
    const currentIndex = filteredTopics.value.findIndex(
      topic => topic.id === selectedTopic.value!.id
    );
    
    if (currentIndex < filteredTopics.value.length - 1) {
      selectTopic(filteredTopics.value[currentIndex + 1].id);
    }
  };

  return {
    // 状态
    topics,
    selectedTopic,
    domains,
    selectedDomain,
    filteredTopics,
    loading,
    error,
    pagination,

    // 方法
    fetchTopics,
    getTopicById,
    fetchStats,
    selectTopic,
    selectDomain,
    initialize,
    createTopic,
    updateTopic,
    deleteTopic,
    reviewTopic,
    starTopic,
    changePage,
    changePageSize,
    goToPreviousTopic,
    goToNextTopic,

    // 枚举
    difficultiesENUM,
    DomainsENUM,
    ReviewStatusENUM,
  };
};
